import json
import math
from tools import replaces, requests, thresholds
from tools.integrates import SignRequest


class DataProcess:
    sign_request = SignRequest()
    history_data = {}

    def __init__(self, vehicle_name):
        self.request_body = requests[vehicle_name]
        self.judge_threshold = thresholds[vehicle_name]
        self.replace_field = replaces[vehicle_name]

    def process(self):
        query_data = self.query(self.request_body)
        replace_data = self.replace(query_data)
        return replace_data

    def query(self, request_body):
        try:
            resp = self.sign_request.post(
                "/open-api/supos/oodm/v2/attribute/current", request_body
            )

            query_data = json.loads(resp.text)  # type: ignore
            if query_data["code"] == 200:
                return query_data["data"]
            else:
                return {"The client request was failed!"}
        except Exception as exp:
            print("supos query data failure!" + str(exp))
            return {"supos query data failure!"}

    def replace(self, query_data):
        replace_data = {}
        for index, value in query_data.items():
            if query_data[index]:
                replace_data[self.replace_field[index]] = value["value"]
            else:
                replace_data[self.replace_field[index]] = None

            if self.replace_field[index] in self.history_data:
                self.history_data[self.replace_field[index]].insert(
                    0, replace_data[self.replace_field[index]]
                )
            else:
                self.history_data[self.replace_field[index]] = []
                self.history_data[self.replace_field[index]].insert(
                    0, replace_data[self.replace_field[index]]
                )

        return replace_data
